from typing import Optional, List
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus

from modules.system.models.menu import Permission
from modules.system.schemas.menu_schemas import MenuCreate, MenuUpdate
from modules.system.params.menu_params import MenuQuery


class MenuRepository(CRUDPlus[Permission]):
    """菜单/权限仓储类"""

    async def get_by_id(self, db: AsyncSession, pk: int) -> Optional[Permission]:
        """按主键获取实体，由上层决定业务过滤"""
        return await self.select_model_by_column(db, id=pk)

    async def create(self, db: AsyncSession, data: MenuCreate) -> Permission:
        """创建菜单/权限，直接委托通用创建方法"""
        return await self.create_model(db, data)

    async def update(self, db: AsyncSession, pk: int, data: MenuUpdate) -> Optional[Permission]:
        """更新菜单/权限，更新后按主键返回 ORM 实体，便于上层刷新"""
        await self.update_model(db, pk, data)
        return await self.select_model(db, pk)

    async def delete(self, db: AsyncSession, pk: int) -> bool:
        """删除菜单/权限"""
        return await self.delete_model(db, pk)

    async def select_by_query(self, db: AsyncSession, query_params: MenuQuery) -> List[Permission]:
        """执行查询并返回 ORM 行列表（可用于构建树等场景）"""
        from utils.query_builder import build_select_stmt
        stmt = build_select_stmt(Permission, query_params)
        stmt = stmt.order_by(Permission.sort.asc(), Permission.id.asc())
        res = await db.execute(stmt)
        return res.scalars().all()


menu_dao = MenuRepository(Permission)